<template>
	<view class="uni-drawer" :class="{
		'uni-drawer--visible': visible,
		'uni-drawer--right': mode === 'right',
		'uni-drawer--left': mode === 'left'
	}" @touchmove.stop.prevent="() => {}">
		<view class="uni-drawer__mask" :class="{
			'uni-drawer__mask--visible': visible
		}" @click="close" v-if="mask"></view>
		<view class="uni-drawer__content" :class="[
			`uni-drawer__content--${mode}`,
			{
				'uni-drawer__content--visible': visible
			}
		]" :style="contentStyle">
			<slot></slot>
		</view>
	</view>
</template>

<script>
/**
 * uni-drawer 抽屉
 * @description 抽屉侧滑菜单
 */
export default {
	name: 'uni-drawer',
	props: {
		// 显示模式（左、右），只在初始化生效
		mode: {
			type: String,
			default: 'left'
		},
		// 是否显示遮罩
		mask: {
			type: Boolean,
			default: true
		},
		// 点击遮罩是否关闭
		maskClick: {
			type: Boolean,
			default: true
		},
		// 抽屉宽度
		width: {
			type: [Number, String],
			default: 220
		},
		// 是否显示
		value: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			visible: false
		};
	},
	computed: {
		contentStyle() {
			return {
				width: this.width + 'px'
			};
		}
	},
	watch: {
		value: {
			immediate: true,
			handler(newVal) {
				this.visible = newVal;
			}
		},
		visible(newVal) {
			this.$emit('input', newVal);
			this.$emit('change', newVal);
		}
	},
	methods: {
		// 关闭抽屉
		close() {
			if (this.maskClick) {
				this.visible = false;
			}
		},
		// 打开抽屉
		open() {
			this.visible = true;
		}
	}
};
</script>

<style scoped lang="scss">
.uni-drawer {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 999;
	pointer-events: none;
	
	&--visible {
		pointer-events: auto;
	}
	
	&__mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.4);
		opacity: 0;
		transition: opacity 0.3s;
		
		&--visible {
			opacity: 1;
		}
	}
	
	&__content {
		position: absolute;
		top: 0;
		bottom: 0;
		background-color: #fff;
		transition: transform 0.3s;
		overflow-y: auto;
		
		&--left {
			left: 0;
			transform: translateX(-100%);
			
			&.uni-drawer__content--visible {
				transform: translateX(0);
			}
		}
		
		&--right {
			right: 0;
			transform: translateX(100%);
			
			&.uni-drawer__content--visible {
				transform: translateX(0);
			}
		}
	}
}
</style>